import React, { useState } from "react";
import { Button, message } from "antd";
import { Compress } from "../compress/index";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import "./index.css";

export const Tools = ({ file, imageUrl }) => {
  const navigate = useNavigate();
  // 自定义 Hook 是一个函数，其名称以 “use” 开头，函数内部可以调用其他的 Hook。
  const [toolsArr] = useState(["压缩", "裁剪"]);
  const [quality] = useState();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const compress = async () => {
    const res = await axios.get("http://localhost:3005/compressionImg", {
      params: {
        quality: quality || 1,
        path: file.response,
      },
      responseType: "arraybuffer",
    });

    const blob = new Blob([res.data], { type: "image/jpeg" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = file.fileName;
    link.click();
    URL.revokeObjectURL(url);
    message.success("压缩成功");
    setIsModalOpen(false);
  };

  function handleButtonClick(tool) {
    if (tool === "裁剪") {
      // 转换为File对象
      if (file) {
        const uploadedImage = file.originFileObj;
        const convertedImage = new File([uploadedImage], uploadedImage.name, {
          type: uploadedImage.type,
        });
        window.URL.revokeObjectURL(convertedImage);
        const imageUrl = URL.createObjectURL(convertedImage);
        navigate("/cropping", { state: { imageUrl } });
        return;
      }
      navigate("/cropping");
      
    }
    if (!imageUrl) {
      message.error("请先上传图片");
      return;
    }

    showModal();
  }
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    compress();
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  return (
    <div>
      {toolsArr.map((tool, index) => (
        <Button onClick={() => handleButtonClick(tool, index)} key={index}>
          {tool}
        </Button>
      ))}
      {/* <Cropping
        filePath={filePath}
        fileName={fileName}
        imageUrl={imageUrl}
      ></Cropping> */}
      <Compress
        isModalOpen={isModalOpen}
        handleOk={handleOk}
        handleCancel={handleCancel}
        imageUrl={imageUrl}
        quality={quality}
      ></Compress>
    </div>
  );
};
